package com.wtj.user.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtj.security.domain.LoginUser;
import com.wtj.user.domain.User;
import com.wtj.user.dto.UserPageReq;
import com.wtj.user.dto.UserPageResp;
import com.wtj.user.dto.UserReq;
import com.wtj.user.service.UserService;
import com.wtj.user.mapper.UserMapper;

import com.wtj.utils.JwtUtil;
import com.wtj.utils.RedisUtils;
import com.wtj.utils.ResponseResult;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
* @author wangt
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2024-11-15 22:39:36
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Resource
    private UserMapper userMapper;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public List<UserPageResp> getUserPage(UserPageReq userPageReq) {
        // 创建分页对象 (Page 是 MyBatis-Plus 提供的分页对象)
        Page<User> page = new Page<>(userPageReq.getPageNum(), userPageReq.getPageSize());

        // 构造查询条件
        LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.lambdaQuery();

        // 执行分页查询
        IPage<User> userPage = userMapper.selectPage(page, userLambdaQueryWrapper);

        // 获取分页结果列表
        List<User> userList = userPage.getRecords();
        return BeanUtil.copyToList(userList, UserPageResp.class);

    }

    @Override
    public UserPageResp getUserById(Long id) {
        User userById = userMapper.getUserById(id);
        return BeanUtil.toBean(userById, UserPageResp.class);
    }

    @Override
    public Map<String, String> login(UserReq userReq) {
        User user = BeanUtil.toBean(userReq, User.class);
        // 创建一个UsernamePasswordAuthenticationToken对象，用于存储用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 使用authenticationManager进行认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 如果认证失败，抛出异常
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 将认证结果转换为LoginUser对象
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        // 获取用户ID
        String userId = loginUser.getUser().getId().toString();
        // 生成JWT
        String jwt = JwtUtil.createJWT(userId);

        // 创建一个HashMap对象，用于存储token
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);

        // 将LoginUser对象存储到Redis中
        // 示例：
        // login:1   LoginUser(user=User [Hash = 1324032176, id=1, userName=admin, nickName=超级管理员,
        // password=$2a$10$8VfwUGRIUmWUeUmwoIYedOVys8bSj/Kg/pfRsWCNNwbUmYNlfaFb2, status=0,
        // email=null, phonenumber=null, sex=null, avatar=null, userType=0, createBy=null,
        // createTime=null, updateBy=null, updateTime=null, delFlag=0, serialVersionUID=1])
        String jsonStr = JSONUtil.toJsonStr(loginUser);
        redisUtils.set("login:" + userId, jsonStr);

        // 返回token
        return map;
    }

    @Override
    public void loginOut() {
        // 1.获取用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        // 2.删除redis中的用户信息
        redisUtils.delete("login:" + id);
    }

    @Override
    public void register(UserReq userReq) {
        // 1.转换domain
        User user = BeanUtil.toBean(userReq, User.class);
        // 2.插入数据库
        userMapper.insert(user);
    }
}




